<template>
  <el-upload
    action="#"
    :data="ossKey"
    list-type="picture-card"
    :file-list="fileList"
    :show-file-list="false"
    :http-request="httpRequest"
    :on-change="handleChange"
    :before-remove="handleRemove"
    :on-error="handleUploadError"
    :before-upload="beforeUploadVideo"
  >
    <div v-loading="uploading">
      <template>
        <div
          :style="{
            width: size + 'px',
            height: size + 'px',
            lineHeight: size + 'px'
          }"
        >
          <i class="el-icon-plus"></i>
        </div>
      </template>
    </div>

    <!-- 公共 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <b style="color: #f56c6c">{{ fileType.length ? fileType.join('/') : '视频' }}</b>
      格式文件
      <template v-if="fileSize">
        ，且大小不超过
        <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="multiple">
        ，限制上传
        <b style="color: #f56c6c">{{ limit }}个</b>
      </template>
    </div>
  </el-upload>
</template>

<script>
import axios from 'axios'
import { getOss } from '@/utils/alioss'
import { setUpFileName } from '@/hooks'
export default {
  name: 'UploadVideo',
  props: {
    // 值
    value: {
      type: [String, Array],
      default() {
        return []
      }
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 视频显示大小
    size: {
      type: Number,
      default: 150
    },
    // 大小限制(MB)
    fileSize: {
      type: Number
    },
    // 响应处理函数
    responseFn: Function,
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => []
    },
    // 是否显示上传成功的提示
    isShowSuccessTip: {
      type: Boolean,
      default: true
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 弹窗标题
    title: String,
    // 图片懒加载
    lazy: {
      type: Boolean,
      default: false
    },
    // 设置上传的请求头部(同官网)
    headers: Object,
    // 文件个数显示(同官网)
    limit: Number,
    // 	支持发送 cookie 凭证信息 (同官网)
    withCredentials: {
      type: Boolean,
      default: false
    },
    // 是否支持多选文件 (同官网)
    multiple: {
      type: Boolean,
      default: false
    },
    // 上传时附带的额外参数(同官网)
    data: Object,
    // 上传的文件字段名 (同官网)
    name: {
      type: String,
      default: 'file'
    },
    // 接受上传的文件类型（thumbnail-mode 模式下此参数无效）(同官网)
    accept: String
  },
  data() {
    return {
      ossKey: {
        key: '',
        bucketName: '',
        objPath: '',
        policy: '',
        signature: ''
      },
      uploading: false,
      fileList: []
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType.length || this.fileSize)
    },
    computedValues() {
      if (this.value) {
        if (typeof this.value === 'string') {
          return [this.value]
        } else {
          return [...this.value]
        }
      } else {
        return []
      }
    },
    isShowUpload() {
      if (this.multiple) {
        return true
      } else {
        return this.computedValues.length === 0
      }
    },
    successFiles() {
      return this.fileList.filter(file => file.status === 'success')
    }
  },
  methods: {
    // 视频上传
    beforeUploadVideo(file) {
      let isVideo = false
      if (this.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isVideo = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      } else {
        isVideo = file.type.indexOf('video') > -1
      }
      if (!isVideo) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}视频格式文件!`)
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传视频大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
    },
    async httpRequest({ file }) {
      this.uploading = true

      const policyData = await getOss()
      let ossUrl = 'https://oss.wasaiyouxuan.com' //填写自己OSS服务器的地址
      let accessUrl = policyData.objPath + '/' + setUpFileName(file) //设置上传的访问路径
      let fromData = new FormData() // 上传文件的data参数

      // form提交
      fromData.append('OSSAccessKeyId', 'LTAI5tATQrBDh3vWLfLAxgHT')
      fromData.append('policy', policyData.policy)
      fromData.append('Signature', policyData.signature)
      fromData.append('bucketName', policyData.bucketName)
      fromData.append('key', accessUrl)
      fromData.append('objPath', policyData.objPath)
      fromData.append('success_action_status', 200)
      fromData.append('file', file)

      await axios.post(ossUrl, fromData)

      if (this.isShowSuccessTip) {
        this.$message.success('上传成功')
      }

      let videoUrl = `${ossUrl}/${accessUrl}`

      console.log(videoUrl)

      this.$emit('input', videoUrl)
    },
    handleChange(file, fileList) {
      this.uploading = false
      this.fileList = fileList
      this.$emit('on-change')
    },
    // 上传失败
    handleUploadError(err) {
      this.uploading = false
      this.$message.error('上传失败, 请重试')
      this.$emit('error', err)
    },
    // 删除视频
    handleRemove(index) {
      if (this.multiple) {
        const data = [...this.computedValues]
        data.splice(index, 1)
        this.fileList.splice(index, 1)
        this.$emit('input', data || [])
      } else {
        this.$emit('input', '')
        this.fileList = []
      }
    }
  }
}
</script>
